package com.factory.manager.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.factory.common.bean.Manager;
import com.factory.common.core.BaseServiceImpl;
import com.factory.common.mapper.ManagerMapper;
import com.factory.common.pojo.Result;
import com.factory.common.utils.StringUtil;
import com.factory.manager.constant.ManagerConstant;
import com.factory.manager.service.ManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@Service
@Slf4j
public class ManagerServiceIml extends BaseServiceImpl<Manager> implements ManagerService {

    @Autowired
    private ManagerMapper managerMapper;

    @Autowired
    private HttpServletRequest request;

    @Override
    protected BaseMapper<Manager> getBaseMapper() {
        return this.managerMapper;
    }

    @Override
    public Result login(String account, String password) {
        try {
            //编码
            String encode = DigestUtils.md5DigestAsHex(password.getBytes());
            Manager manager = managerMapper.selectOne(new QueryWrapper<Manager>().eq("account",account));
            if (null == manager) {
                return Result.fail("用户不存在");
            }

            if (encode.equalsIgnoreCase(manager.getPassword())) {
                String token = StringUtil.getUUID();
                request.getSession().setAttribute(ManagerConstant.getToken(token), manager);
                JSONObject json = new JSONObject();
                json.put(ManagerConstant.MANAGERTOKEN, token);
                json.put("manager", manager);
                return Result.success(json, "登录成功");
            } else {
                return Result.fail("密码不正确");
            }

        } catch (Exception e) {
            log.error("{}", e);
        }
        return Result.fail("服务异常");
    }

    @Override
    public Result logout() {
        String token = request.getHeader(ManagerConstant.MANAGERTOKEN);
        if(StringUtil.notEmpty(token)){
            request.getSession().removeAttribute(ManagerConstant.getToken(token));
        }

        return Result.success(null,"退出登录成功!");
    }

    @Override
    public Optional<Manager> getLoginUser() {
        String token = request.getHeader(ManagerConstant.MANAGERTOKEN);
        if (StringUtil.notEmpty(token)) {
            Object o = request.getSession().getAttribute(ManagerConstant.getToken(token));
            if (null != o) {
                return Optional.of((Manager) o);
            }
        }
        return Optional.empty();
    }
}
